package com.bwie.config;

import com.bwie.utils.TelSmsUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;

@Configuration
@Log4j2
public class SendMessage {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Bean
    public Queue initQueue(){
        return new Queue("sendMessage",true);
    }


    @RabbitListener(queues = "sendMessage")
    public void sendMessage(String msg, Message message, Channel channel){
        String messageId = message.getMessageProperties().getMessageId();
        Long count = redisTemplate.opsForSet().add("sms101", messageId);
        if (count == 1){
            try {
                String code="退款成功";
                TelSmsUtils.sendSms(msg,"sms0001",new HashMap<String, String>(){{
                    put("code",code);
                }});
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
                System.out.println("消息队列消费成功");
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("消费异常");
            }
        }else {
            log.info("消息队列:【sendMessage】,消息内容:{}消费重复了",msg);
        }
    }

}
